package com.anosine.gpsl.android.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.anosine.gpsl.android.AppConstants;
import com.anosine.gpsl.android.GPSLApp;
import com.anosine.gpsl.android.R;
import com.anosine.gpsl.android.WebConstants;
import com.anosine.gpsl.android.base.BaseFragment;
import com.anosine.gpsl.android.entity.DelHistoryWork;
import com.anosine.gpsl.android.entity.Login;
import com.anosine.gpsl.android.entity.UpdataInfoBean;
import com.anosine.gpsl.android.entity.UpdateBean;
import com.anosine.gpsl.android.ui.activity.AddFamilyNumberActivity;
import com.anosine.gpsl.android.ui.activity.FamilyNumberActivity;
import com.anosine.gpsl.android.ui.activity.FeedBackActivity;
import com.anosine.gpsl.android.ui.activity.HelpActivity;
import com.anosine.gpsl.android.ui.activity.LoginActivity;
import com.anosine.gpsl.android.ui.activity.MipcaActivityCapture;
import com.anosine.gpsl.android.ui.activity.ModifyPwdActivity;
import com.anosine.gpsl.android.ui.activity.MoveHistoryBaiduMapActivity;
import com.anosine.gpsl.android.ui.activity.OfflineActivity;
import com.anosine.gpsl.android.ui.activity.RegisterActivity;
import com.anosine.gpsl.android.ui.activity.UserInfoActivity;
import com.anosine.gpsl.android.ui.activity.RegAgreementActivity;
import com.anosine.gpsl.android.util.ActivityFrgManager;
import com.anosine.gpsl.android.util.HttpRequestListener;
import com.anosine.gpsl.android.util.SendHttpUtils;
import com.anosine.gpsl.android.util.ToastHelper;
import com.anosine.gpsl.android.util.UserInfoProxy;
import com.anosine.gpsl.android.util.zxing.view.CameraManager;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.http.RequestParams;


/**
 * @Title: TabMineFragment
 * @Package com.anosine.gpsl.android.ui.fragment
 * @Description: 我的界面
 * @author: sunny
 * @date: 2015-11-23
 * @version V1.0
 */
public class TabMineFragment extends BaseFragment implements View.OnClickListener{

    private final static int SCANNIN_GREQUEST_CODE	= 1;

    /**
     * 方法名：onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
     * 功	能：创建该Fragment的视图
     * 参	数：LayoutInflater inflater LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化
     *  ViewGroup container ViewGroup是Layout的基类, Bundle savedInstanceState
     * 返回值： View view
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main_tab_mine, container, false);
        view.findViewById(R.id.tv_main_more_item1).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_item2).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_modify_pwd).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_history_work).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_del_history_work).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_item4).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_item5).setOnClickListener(this);
        view.findViewById(R.id.btn_mine_set).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_downmap).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_add_familynumber).setOnClickListener(this);
        view.findViewById(R.id.tv_main_more_feedback).setOnClickListener(this);

        return view;
    }
    /**
     * 方法名 ：onClick(View view)
     * 功	能：是android.view.View.OnClickListener这个接口中的函数，如果你设置了按钮监听，当你点击按钮的时候，就会进入到OnClick函数中，然后通过你的按钮ID找到对应的按钮做操作
     * 参	数：View view ，一个view类型的参数传入，当一个view类对象被点击时会触发该事件
     * 返回值：无
     * */
    @Override
    public void onClick(View view) {
        switch (view.getId()){
        	case R.id.tv_main_more_feedback:
        		//意见反馈
        		Intent i=new Intent(getActivity(),FeedBackActivity.class);
        		startActivity(i);
        		break;
        	case R.id.tv_main_more_add_familynumber:
        		//添加亲情号
        		Intent intent1=new Intent(getActivity(),FamilyNumberActivity.class);
        		startActivity(intent1);
        		break;        		
        	case R.id.tv_main_more_downmap:
        		//下载地图离线包        		
        		Intent intent = new Intent(getActivity(),
        				OfflineActivity.class);
    			startActivity(intent);
        		break;
            case R.id.tv_main_more_item1:
                clickBtnUpdate();
                break;
                //个人信息
            case R.id.tv_main_more_item2:
            	ShowInputPasswordDlg.showDlg(getChildFragmentManager(), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String value= (String) view.getTag();                          
                        startActivity(new Intent(getActivity(), UserInfoActivity.class));
                    }
                }, "请重新输入密码");
                
                break;
            case R.id.tv_main_more_modify_pwd:
            	//修改密码
                startActivity(new Intent(getActivity(), ModifyPwdActivity.class));
                break;
            case R.id.tv_main_more_history_work:
//            	ShowInputPasswordDlg.showDlg(getChildFragmentManager(), new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
                        String value= (String) view.getTag();                          
                        startActivity(new Intent(getActivity(), MoveHistoryBaiduMapActivity.class));
//                    }
//                }, "请重新输入密码");
                break;
            case R.id.tv_main_more_item4:
                clickBtnItem4();
                break;
            case R.id.tv_main_more_item5:
            	//帮助
                startActivity(new Intent(getActivity(), HelpActivity.class));
                break;
            case R.id.btn_mine_set:            	
            	clickBtnLoginOut();
                break;
            case R.id.tv_main_more_del_history_work:
            	ShowInputPasswordDlg.showDlg(getChildFragmentManager(), new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        String value= (String) view.getTag();                          
                    	clickBtnDelHistoryWork();
                    }
                }, "请重新输入密码");
            	break;
        }
    }
    
    private void clickBtnLoginOut() {
        ActivityFrgManager.getInstance().finishActivities();
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        Login userInfo = UserInfoProxy.getInstance().getLoginInfo();
        if (userInfo != null) {
            userInfo.isLoginAuto = false;
            UserInfoProxy.getInstance().setLoginUserInfo(userInfo);
        }
        startActivity(intent);
        getActivity().finish();
    }
    /**
     * 方法名：clickBtnDelHistoryWork()
     * 功	能：删除历史轨迹记录
     * 参	数：无
     * @return 无
     */

    private void clickBtnDelHistoryWork() {    	
    	  Login info= UserInfoProxy.getInstance().getLoginInfo();   
    	  boolean isHaveAdmin=false;
          if (info!=null){
        	  for(int i=0;i<GPSLApp.mActive.size();i++){
        		  if((GPSLApp.mActive.get(i).hid).equals(info.holdid)){
        			  isHaveAdmin=true;
        			  RequestParams params = new RequestParams();
                      params.addBodyParameter("usermd5",info.userMd5);
                      params.addBodyParameter("objectid",info.objectid );
                      SendHttpUtils sendHttp=new SendHttpUtils();
                      TypeToken type = new TypeToken<DelHistoryWork>() {
                      };
                      String url=String.format("%1s/%2s", AppConstants.sCommonUrl, WebConstants.Do_Del_History_Work_Action);
                      sendHttp.doRequest(url, params, type, new HttpRequestListener<DelHistoryWork>() {
                         
                      	/**
                      	 * 方法名：onSuccess(String result, final UpdateBean t)
                      	 * 功	能：json解析成功后进行的操作
                      	 * 参	数：String result　json数据, final UpdateBean t　解析后的数据
                      	 * @return 无
                      	 */
                      	@Override
                          public void onSuccess(String result, final DelHistoryWork t) {
                              if (t!=null){
                                                                                  	
                                      ShowConfirmDlg.showDlg(getActivity().getSupportFragmentManager(), new View.OnClickListener() {
                                         
                                      	/**
                                      	 * 方法名：onClick(View view)
                                      	 * 功	能：重写弹框的onClick方法即点击事件
                                      	 * 参	数：View view
                                      	 * @return 无
                                      	 * */
                                      	@Override
                                          public void onClick(View view) {
                                      		
                                      		if("msg_delete_suucess".equals(t.message)){
                                      			ToastHelper.toast("删除成功");  
                                      		}else if("msg_delete_nouser".equals(t.message)){
                                      			ToastHelper.toast("车辆与用户不匹配");  
                                      		}else if("msg_delete_null".equals(t.message)){
                                                ToastHelper.toast("车辆信息不存在");  
                                          	}else if("msg_delete_false".equals(t.message)){
                                                ToastHelper.toast("删除失败");  
                                            }
                                      		
                                          }
                                      }, "确定要删除所有历史轨迹吗？", "删除提示",false );
                                  
                              }
                          }

                      	/**
                      	 * 方法名：onFailure(String error)
                      	 * 功	能：解析失败或者加载失败后的操作
                      	 * 参	数：String error　错误信息
                      	 * @return 无
                      	 */
                          @Override
                          public void onFailure(String error) {
                              ToastHelper.toast(error);
                          }
                      });
                      
        		  }
        	  }
        	  if(isHaveAdmin){
        		  
        	  }else{
        		  ToastHelper.toast("您没有权限进行删除！");
        	  }
              
          }
	}
	/**
     * 方法名：getVersionCode()
     * 功	能：获取apk的版本号
     * 参	数：无
     * 返回值：String version 版本号
     */
    private String getVersionCode()  {
        String version = "1";
        try {
            PackageManager packageManager = getActivity().getPackageManager();
            PackageInfo packInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            version = String.valueOf(packInfo.versionName);
        } catch ( Exception e) {
            e.printStackTrace();
        }
        return version;

    }

    /**
     * 方法名：clickBtnUpdate()
     * 功	能：点击更新做的操作
     * 参	数：无
     * 返回值：无
     */
    private void clickBtnUpdate() {
        Login info= UserInfoProxy.getInstance().getLoginInfo();
        if (info!=null){
            showProgressInfo("请求中...");
            RequestParams params = new RequestParams();
            params.addBodyParameter("appid", "201");
            params.addBodyParameter("version", getVersionCode());
            params.addBodyParameter("platform", "Android");
            SendHttpUtils sendHttp=new SendHttpUtils();
            TypeToken type = new TypeToken<UpdateBean>() {};
            String url=String.format("%1s/%2s", AppConstants.sCommonUrl, WebConstants.Do_GetServerNewVersion_Action);
            sendHttp.doRequest(url, params, type, new HttpRequestListener<UpdateBean>() {
               
            	/**
            	 * 方法名：onSuccess(String result, final UpdateBean t)
            	 * 功	能：json解析成功后进行的操作
            	 * 参	数：String result　json数据, final UpdateBean t　解析后的数据
            	 * 返回值：无
            	 */
            	@Override
                public void onSuccess(String result, final UpdateBean t) {
                    dismissProgress();
                    if (t!=null){
                        String version=getVersionCode();
                        if(("0").equals(t.new_version+"")){
                            ToastHelper.toast("当前已经是最新版本");
                    	}else{                           
                    		String[] features = null;
							String feature = "";
							if (t.new_version_feature.contains(";")) {
								features = ((String) t.new_version_feature)
										.split(";");
							} else if (t.new_version_feature
									.contains("；")) {
								features = ((String) t.new_version_feature)
										.split("；");
							}

							try {
								for (int i = 0; i < features.length; i++) {
									feature = feature + features[i]
											+ "\n";
								}
							} catch (Exception e) {
								feature = t.new_version_feature;
							}
//                        	String[] features = ((String) t.new_version_feature).split(",");
//                    		String feature="";
//                    		for(int i=0;i<features.length;i++){
//                    				feature=features[i]+"\n";
//                    			}
                            ShowConfirmDlg.showDlg(getActivity().getSupportFragmentManager(), new View.OnClickListener() {
                               
                            	/**
                            	 * 方法名：onClick(View view)
                            	 * 功	能：重写弹框的onClick方法即点击事件
                            	 * 参	数：Ｖiew view
                            	 * 返回值：无*/
                            	@Override
                                public void onClick(View view) {
                                    if (Environment.getExternalStorageState().equals(
                                            Environment.MEDIA_MOUNTED)) {
                                        UpdataInfoBean info=new UpdataInfoBean();
                                        info.setVersion(String.valueOf(t.new_version));
                                        info.setUrl(t.new_version_url);
                                        info.setDescription(t.new_version_feature+"\n\n");
                                        downloadApk(info);
                                    } else {
                                        ToastHelper.toast("请插入SD卡后重试");
                                    }
                                }
                            }, "\n"+feature,"更新提示", false );
                        }
                    }
                }

            	/**
            	 * 方法名：onFailure(String error)
            	 * 功	能：解析失败或者加载失败后的操作
            	 * 参	数：String error　错误信息
            	 * 返回值：无
            	 */
                @Override
                public void onFailure(String error) {
                    dismissProgress();
                    ToastHelper.toast(error);
                }
            });
        }
    }


    /**
     * 方法名：downloadApk(UpdataInfoBean info)
     * 功	能：下载新的apk
     * 参	数：UpdataInfoBean info　更新的bean
     * 返回值：无
     */
    private void downloadApk(UpdataInfoBean info) {
        ShowDownloadProgressDlg.showDlg(getActivity().getSupportFragmentManager(), info);
    }

    /**
     * 方法名：clickBtnItem4()
     * 功	能：点击二维码扫描后进行的操作
     * 参	数：无
     * 返回值：无
     * */
    private void clickBtnItem4() {
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidth = dm.widthPixels;
        int screenHeigh = dm.heightPixels;
        CameraManager.MIN_FRAME_WIDTH = (int) (0.7f * screenWidth);
        CameraManager.MIN_FRAME_HEIGHT = (int) (0.7f * screenWidth);
        CameraManager.MAX_FRAME_WIDTH = screenHeigh;
        CameraManager.MAX_FRAME_HEIGHT = screenWidth;

        Intent intent = new Intent();
        intent.setClass(getActivity(), MipcaActivityCapture.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
        AppConstants.sQR_CSAN_TIME_OUT = false;
    }
    /**
     * 方法名：onActivityResult(int requestCode, int resultCode, Intent data)
     * 功	能：二维码扫描后的回调操作
     * 参	数：int requestCode　请求码，即调用startActivityForResult()传递过去的值 ,
     *  int resultCode结果码，结果码用于标识返回数据来自哪个新Activity ,
     *  Intent data　通过intent得到新Activity关闭后返回的数据 
     * 返回值：无*/
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    if (bundle != null) {
                        String info = bundle.getString(AppConstants.TAG_BUNDLEKEY_SCAN_RESULT);
                        //异常：werehttp://www.baidu.com
                        //
                        //可跳转，但网页不正常：http://baidu.com
                        if(info.contains("http://")&&"http://".equals(info.subSequence(0,7))){
                        	Uri uri = Uri.parse(info);    
    					    Intent it = new Intent(Intent.ACTION_VIEW, uri);    
    					    startActivity(it);
                        }else{
                        	ToastHelper.toast("扫描结果："+info);
                        }
                    	  
                    }
                }
                break;
        }
    }
	
}
